package com.tingyuge.base.jdk.io.nio.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/12
 * @description
 */
public class PipleDemo {

    public static void main(String[] args) throws IOException {

        //1.获取管道
        Pipe pipe = Pipe.open();

        //2.获取sink通道
        Pipe.SinkChannel sinkChannel = pipe.sink();

        //3.创建缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //4.写入数据
        buffer.put("i'm sink".getBytes());
        buffer.flip();
        sinkChannel.write(buffer);

        //5.获取source通道
        Pipe.SourceChannel source = pipe.source();
        //6.创建缓冲区,读取数据
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);

        int length = source.read(buffer1);
        System.out.println(new String( buffer1.array(),0,length));
        //7.关闭通道
        sinkChannel.close();
        source.close();

    }
}
